function queryStringify(obj) {
  let str = "";
  for (let k in obj) str += `${k}=${obj[k]}&`;
  return str.slice(0, -1);
}

//封装ajax
function ajax(options) {
  let defaultOptions = {
    url: "",
    method: "GET",
    async: true,
    data: {},
    headers: {
      "content-type": "application/x-www-form-urlencoded",
    },
    success: function () {},
    error: function () {},
  };

  let { url, method, async, data, headers, success, error } = {
    ...defaultOptions,
    ...options,
  };

  if (
    typeof data === "object" &&
    headers["content-type"]?.indexOf("json") > -1
  ) {
    data = JSON.stringify(data);
  } else {
    data = queryStringify(data);
  }

  //如果是get请求,并且有参数,那么直接组装一下url信息
  if (/^get$/i.test(method) && data) url += "?" + data;

  //发送请求
  const xhr = new XMLHttpRequest();
  xhr.open(method, url, async);
  xhr.onload = function () {
    // 不是2开头的错误码，直接报错
    if (!/^2\d{2}$/.test(xhr.status)) {
      error(`错误状态码:${xhr.status}`);
      return;
    }
    //执行解析
    try {
      let res = JSON.parse(xhr.responseText);
      success(res);
    } catch (error) {
      error("解析失败！因为后端返回的结果不是json格式字符串");
    }
  };
  //设置请求头内信息
  for (let k in headers) xhr.setRequestHeader(k, headers[k]);
  if (/^get$/i.test(method)) {
    xhr.send();
  } else {
    xhr.send(data);
  }
}

//promise ajax
function pajax(options) {
  return new Promise((resolve, reject) => {
    ajax({
      ...options,
      success(res) {
        resolve(res);
      },
      error(err) {
        reject(err);
      },
    });
  });
}
